import { observable, action, autorun,toJS } from 'mobx';
import * as  Apis from '../apis/govern';
import { ListStore } from './listStore';
import {WeaTableNew,WeaForm} from 'comsMobx';
import { message, Modal } from "antd";
import { ModelStore } from './modelStore';
import { ModalConfirmStore } from './modalConfirmStore';
import { WeaLocaleProvider,WeaTools } from 'ecCom';
import BtnType from '../util/btnType';
const getLabel = WeaLocaleProvider.getLabel;
const {TableStore} = WeaTableNew;

export default class ProStore extends ListStore{
    @observable tasklabels = {};
    @observable condition = [];
    @observable conditionNum = [];
    @observable status = {
        loading: false,
    }
    @observable title = "";
    @observable dataType = false;// 控制页面刷新
    @observable selectedTreeKey = 0;//左侧树key值,为0代表初始化//19.2.22开始给0 lusx
    @observable treeData = [];
    isSelect = false;//顶部表单select框key值改变;
    apisType = Apis.getProList; // 控制table的api
    @observable isSuperSearch = false;//点击pre高级搜索
    @observable noDoAgain = false;//防止任务查询结果页面二次执行搜索方法
    @observable columnsNum = 0;//table表格列数
    @observable pageFrom = ""; //区分页面来源

    @observable  categoryid_count = "";
    @observable  status_count = "";
    @observable  sponsordept_count = "";
    @observable  isContain_count = {"isContain":"","pStatus":"","psponsordept":"","ptype":"","sqlWhereDate":""}
    @observable baseSearchValue = ''
    @observable isTreeShow = true;//督办类型树是否默认展示

    constructor(props) {
        super(props);
        window.showSpaModel = this.showSpaModel;
        this.getcolumnsNum = this.getcolumnsNum.bind(this);
        this.clear = this.clear.bind(this);
    }
    @action
    setDataType(dataType) {
        this.dataType = dataType;
        this.noDoAgain = false;
        if (dataType == "0") {
            this.title = `${getLabel('388513','责任事项')}`;
            this.apisType = Apis.getProListResult;
            this.pageFrom = "project";
        } else if (dataType == "1") {
            this.title = `${getLabel('388797','代发事项')}`;
            this.apisType = Apis.getProListResult;
            this.pageFrom = "project";
        } else if (dataType == "2") {
            this.title = `${getLabel('132194','监控列表')}`;
            this.apisType = Apis.getProListResult;
            this.pageFrom = "project";
        } else if (dataType == "3") {
            this.title = `${getLabel('16413,356','查询项目结果')}`;
            this.apisType = Apis.getProListResult;
            this.pageFrom = "project";
            this.noDoAgain = true;
        }else if (dataType == "4") {
            this.title = `${getLabel('130307','我的督办')}`;
            this.apisType = Apis.getProListResult;
            this.pageFrom = "project";
        }else if (dataType == "15"){//新增 督办台账 我负责
            this.apisType = Apis.getProAccountResult;
            this.pageFrom = "account";
        }else if (dataType == "5"){//新增 督办台账 我参与
            this.apisType = Apis.getProAccountResult;
            this.pageFrom = "account";
        }else if (dataType == "6"){//新增 督办台账 我发起
            this.apisType = Apis.getProAccountResult;
            this.pageFrom = "account";
        }else if (dataType == "7"){//新增 督办台账 事项查询
            this.apisType = Apis.getProAccountResult;
            this.pageFrom = "account";
        }else if (dataType == "8"){//主办事项
            this.apisType = Apis.getProFeedBack;
            this.pageFrom = "feed";
        }else if (dataType == "9"){//协办事项
            this.apisType = Apis.getProFeedBack;
            this.pageFrom = "feed";
        }else if (dataType == "10"){//全部（主办+协办）
            this.apisType = Apis.getProFeedBack;
            this.pageFrom = "feed";
        }else if (dataType == "11"){//待阅反馈
            this.apisType = Apis.getProFeedBack;
            this.pageFrom = "feed";
        }else if (dataType == "12"){//已阅反馈
            this.apisType = Apis.getProFeedBack;
            this.pageFrom = "feed";
        }else if (dataType == "13"){//全部（待阅+已阅）
            this.apisType = Apis.getProFeedBack;
            this.pageFrom = "feed";
        }else if (dataType == "14"){//反馈查询
            this.apisType = Apis.getProFeedBack;
            this.pageFrom = "feed";
        }else{
            this.title = `${getLabel('388406,30947','事项查询')}`;
            this.apisType = Apis.getProListResult;
            this.pageFrom = "project";
        }
    }

    @action
    initTreeData() {
        Apis.getTreeDatas().then(data => {
            if(parseInt(data.status) == 1){
                this.treeData = data.categotyData;
            }else{
              message.error(data.error);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    @action
    getIsTreeShow() {
        Apis.getIsTreeShow().then(data => {
            if (parseInt(data.status) == 1) {
                this.isTreeShow = data.isTreeShow;
            } else {
                message.error(data.error);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    //左侧树的点击事件
    @action
    setSelectedTreeKey = (key) => {
        if (key != this.selectedTreeKey) {
            this.baseSearchValue = '';
            this.loading = true;
            this.isSelect = true;
            this.form.resetForm();
            this.selectedTreeKey = key;
            this.noDoAgain =false;//切换左侧树，table列表不切换18.12.25
            this.init({"categoryid": key,pageFrom:this.pageFrom});
            // console.log("key",key,this.selectedTreeKey);
        }
    }

    @action
    onCollapse = (bool) => {
        this.isTreeShow = bool;
    }

    @action
    setKey1 = (key) => {
        this.categoryid_count = key;
    }
    @action
    setKey2 = (key) => {
        this.status_count = key;
    }
    @action
    setKey3 = (key) => {
        this.sponsordept_count = key;
    }
    @action
    setKey4 = (param) => {
        this.isContain_count = param;
    }
    //左侧树的点击事件
    @action
    setTitle = (key) => {
        if (key != this.selectedTreeKey) {
            this.title = key;
        }
    }

    @action
    setDoAgain(bool){
        this.noDoAgain = bool;
    }
    /**
     * 初始化页面
     * @param isSuper  请求接口参数
     * @param isSuperPage  当前页面是否高级搜索页面
     * @param fromSuperPage  当前页面是否来自高级搜索页面
     */
    @action
    init(params){
        this.isSuperSearch = _.has(params,'isSuperSearch') ? params.isSuperSearch : false;
        //初始化顶部表单
        let newParams = {"isSuper":"0","isSuperPage":false,"fromSuperPage":false,"categoryid":this.selectedTreeKey||params.selectedTreeKey,"isSelect":this.isSelect,...params,pageFrom:this.pageFrom,dataType:this.dataType};
        this.getProListConditions(newParams);
        //初始化搜索面板
        params.isSuperPage ? null : this.getSearchPanel();
        //初始化表格
        params.isSuperPage ? null : (this.noDoAgain ? null : this.doSearch(newParams) );
        //初始化左侧树
        params.isSuperPage ? null : this.initTreeData();
        //清除数据
        this.clearFormFields();
        this.baseSearchValue = "";
    }


    @action
    initCount(params){
        this.isSuperSearch = _.has(params,'isSuperSearch') ? params.isSuperSearch : false;
        //初始化顶部表单
        let newParams = {"isSuper":"0","isSuperPage":false,"fromSuperPage":false,"categoryid":this.selectedTreeKey||params.selectedTreeKey,"isSelect":this.isSelect,...params,pageFrom:this.pageFrom,dataType:this.dataType};
        this.getProListConditions(newParams);
        //初始化搜索面板
        params.isSuperPage ? null : this.getSearchPanel();
        //初始化左侧树
        params.isSuperPage ? null : this.initTreeData();
        //清除数据
        this.clearFormFields();
    }


    @action
    getProListConditions(params){
        this.condition = [];
        this.conditionNum = [];
        this.form = new WeaForm();
        this.formB = new WeaForm();//lusx 19.3.26 督办查询首次进入页面报filed is not select...
        this.status.loading = true;
        const isSelect = this.isSelect;
        Apis.getProListConditions(params).then(data=>{
            if(parseInt(data.status) == 1){
                //|| (params.selectedTreeKey == 0 ? params.selectedTreeKey : this.selectedTreeKey)
              if(params.fromSuperPage === true || isSelect === true ){//三目->回退时渲染pre高级搜索
                  this.condition= data.searchCondition;
                  this.form && !this.form.isFormInit && this.form.initFormFields(data.searchCondition);
              }else if(params.isSuperPage){//pre高级搜索
                  this.conditionNum= data.searchCondition;
                  //this.formB && !this.formB.isFormInit && this.formB.initFormFields(data.searchCondition);
                  this.formB && !this.formB.isFormInit && this.formB.initFormFields(data.searchCondition);
              }
            }else{
              message.error(data.error);
            }
             this.status.loading = false;
         })
         .catch(error => {
            message.error(error);
          });
    }
    /*
     * 顶部表单，select的key值改变，执行方法
    */
   @action
   handleChange(){
       this.isSelect = true;
       const searchParamsAd = this.form.getFormParams();
       const params = { "categoryid":this.selectedTreeKey,"isSelect":this.isSelect,...searchParamsAd,pageFrom:this.pageFrom,dataType:this.dataType};
       this.form = new WeaForm();
       this.getProListConditions(params);
       this.getSearchPanel();
   }
    //搜索面板
    @action
    getSearchPanel(params){
        this.conditionNum = [];
        const newParams = {"isSuper":"1","categoryid":this.selectedTreeKey,pageFrom:this.pageFrom,dataType:this.dataType};
        Apis.getProListConditions(newParams).then(data=>{
            if(parseInt(data.status) == 1){
              this.conditionNum= data.searchCondition;
              this.formB && !this.formB.isFormInit && this.formB.initFormFields(data.searchCondition);
            }else{
              message.error(data.error);
            }
            this.status.loading = false;
        })
        .catch(error => {
            message.error(error);
        });
    }
    @action
    clearFormFields(){
        this.formB.resetForm();
        this.form.resetForm();
        this.isSelect = false;//顶部表单select框key值改变;
        this.isSuperSearch = false;//点击pre高级搜索
    }
   @action
   doSearch(params){

    let countParams = {};
    if(this.categoryid_count && this.categoryid_count !=""){ //督办类型统计
        countParams = { fromSuperPage: false, "categoryid": this.selectedTreeKey, "isSuperSearch": true, "count_categoryid": this.categoryid_count};
    }else if(this.status_count && this.status_count !=""){ //督办状态统计
        countParams = { fromSuperPage: false, "categoryid": this.selectedTreeKey, "isSuperSearch": true, "count_status": this.status_count};
    }else if(this.sponsordept_count && this.sponsordept_count !=""){ //督办单位统计
        countParams = { fromSuperPage: false, "categoryid": this.selectedTreeKey, "isSuperSearch": true, "count_sponsordept": this.sponsordept_count};
    }else if(this.isContain_count && this.isContain_count.isContain !=""){ //整体统计
        const pStatus = this.isContain_count.pStatus || "";
        const psponsordept = this.isContain_count.psponsordept || "";
        const ptype = this.isContain_count.ptype || "";
        const sqlWhereDate = this.isContain_count.sqlWhereDate|| "";
        countParams = { fromSuperPage: false, "categoryid": this.selectedTreeKey, "isSuperSearch": true, "isContain": this.isContain_count.isContain, "pstatus": pStatus, "psponsordept": psponsordept, "ptype": ptype, "sqlWhereDate": sqlWhereDate};
    }

    this.status.loading = true;
    if(params.isSuper && params.isSuper === "1" ){
    this.noDoAgain = true;
    }else{
        this.noDoAgain =false;
    }
    //获取表单的value
     let searchFormParams = {};
     let newParams = {};
     let preParams = {"dataType":this.dataType};
     if ((_.has(params,'fromSuperPage') && params.fromSuperPage == true && params.isSuperSearch == true )) {//高级搜索
         searchFormParams = this.formB.getFormParams();
         newParams = {...searchFormParams,"isSuper":"1"};
     }else{
         searchFormParams = this.form.getFormParams();
    }
    //顶部表单搜索
    if (_.has(searchFormParams,"selectKey")) {
        let omitNewParams =  _.omit(searchFormParams, ['selectKey']);
        let keys = Object.keys(omitNewParams);
        if(searchFormParams["selectKey"] == ""){
            let pick = _.pick(searchFormParams, keys);
            newParams = _.mapKeys(pick, (value, key)=> {
                 return key==keys[keys.length-1]?"selectValue":key
             });
        }else if (searchFormParams["selectKey"]) {
            newParams = _.mapKeys(searchFormParams,(value,key)=>{
                return key == keys[keys.length-1]?"selectValue":key
            })
        }
    }
    newParams = {...preParams,...params,...newParams,...countParams};
    this.apisType(newParams).then(data=>{
         this.tableStoreDbInquire.getDatas(data.sessionkey,  1);
        //  console.log("tableStore",JSON.stringify(this.tableStoreDbInquire));
         //console.log(this.tableStoreDbInquire);
         this.status.loading = false;
     })
     this.formB.resetForm()
   }
   @action
   doSearchAccount(params){
        this.apisType(params).then(data=>{
            // this.tableStoreDbInquire.getDatas(data.sessionkey,  1);
            // console.log("tableStore",JSON.stringify(this.tableStoreDbInquire));
            this.tableStoreDbInquire.reloadCurrent();
            this.status.loading = false;
        })
        this.formB.resetForm()
   }

    @action
   doSearchAccount2(params){
        this.apisType(params).then(data=>{
            this.tableStoreDbInquire.getDatas(data.sessionkey,  1);
            // console.log("tableStore",JSON.stringify(this.tableStoreDbInquire));
            // this.tableStoreDbInquire.reloadCurrent();
            this.status.loading = false;
        })
        this.formB.resetForm()
   }

   /**
     * 触发方式（0卡片触发、1触发流程）（key 0新建、1汇报、2分解、3催办、4变更）
     * @param {*} params
     */
    @action
    getActionSetting(taskId, key) {
        let _this= this;
        Apis.getActionSetting({"taskid":taskId,"actiontype":key}).then(data => {
          if(parseInt(data.status) == 1){
            if(data.isShowModel){
                _this.showModel(taskId, key);
            }else{
                if(data.status=="-1"){
                    message.error(data.error);
                }else{
                    window.open("/spa/workflow/index_form.jsp#/main/workflow/req?requestid="+data.newrequestid+"&workflowid="+data.flowid+"&taskid="+taskId+"&actiontype="+key);
                }
            }
          }else{
            message.error(data.error);
          }
        }).catch(error => {
            message.error(error);
        });
    }

    @observable id = "";
    @observable modelType = "";
    @observable modelStore = new ModelStore();
    @observable confirmVisible = false;
    @observable modalConfirmStore = new ModalConfirmStore();
    @observable content = "";
    /**
     * 弹窗动作执行方法
     * @param {*} id
     * @param {*} modelType
     */
    @action
    showModel(id, modelType) {
        this.id = id;
        this.modelType = modelType;
        this.modelStore.handleShareDialog(true);
        this.modelStore.initModel(this.modelType, id);
        this.modelStore.form = new WeaForm();
    }

    showSpaModel = (id, modeType) => {
        this.id = id;
        this.modelType = modeType;
        this.modelStore.showSpaModel(id, modeType);
    }

    /**
     * 弹窗动作执行方法
     * @param {*} id
     * @param {*} modelType
     */
    @action
    showconfirm(id, modelType, title, content) {
        this.id = id;
        this.modelType = modelType;
        this.modelStore.showConfirm({ id, modelType, title, content });
    }

    /**
     * 弹窗动作执行方法
     * @param {*} id
     * @param {*} modelType
     */
    @action
    showConfirmBatch(id, modelType, title, content, refreshList) {
        this.modelType = modelType;
        let param = { id, modelType, title, content };
        if(refreshList){
            param.callBack = this.onSearch;
        }
        // console.log("ids123",JSON.stringify(param) );
        this.modelStore.showConfirmBatch(param);
    }


    /**
     * 点击搜索刷新列表
     */
    onSearch = (value) => {
        let params = { "dataType": this.dataType, "fromSuperPage": false, "isSelect": true, "isSuper": "0", "isSuperPage": false, "selectKey": "name", "selectValue": value, "selectedTreeKey": this.selectedTreeKey }
        this.doSearchAccount({ ...params })
    }

     onSearch2 = (value) => {
        let params = { "dataType": this.dataType, "fromSuperPage": true, "isSuper": "1", "isSuperPage": true, "name": value, "categoryid": this.selectedTreeKey }
        this.doSearchAccount2({ ...params })
    }

    exportAccountExcel(ids, modelType, title, content,categoryid){
        this.modelType = modelType;
        let _this = this;
         Modal.confirm({
            cancelText: `${getLabel(201,'取消')}`,
            okText: `${getLabel(826,'确定')}`,
            title: title,
            content: content,
            onOk() {
               let taskids= ids.join(",");
               let url = "/api/govern/task/exportProAccountExcel?categoryid="+categoryid+"&taskids="+taskids + "&pageFrom=" + _this.pageFrom + "&dataType=" + _this.dataType ;
                window.location.href = url;
            },
            onCancel() { },
        });
    }

    exportGovernExcel =(ids, modelType, title2, content,categoryid,type,title) =>{
        let Base64 = WeaTools.Base64;
        this.modelType = modelType;
        let _this = this;
        let datatype = '';
        let sheetname = "&sheetname="+ encodeURIComponent(Base64.encode(_this.title));
        if(type==3){
            datatype = "&datatype="+_this.dataType;
        }
        if(title){
            sheetname = "&sheetname="+encodeURIComponent(Base64.encode(title));
        }
         Modal.confirm({
            cancelText: `${getLabel(201,'取消')}`,
            okText: `${getLabel(826,'确定')}`,
            title: title2,
            content: content,
            onOk() {
               let taskids= ids.join(",");
               let url = "/api/govern/task/exportGovernExcel?type="+type+"&categoryid="+categoryid+"&taskids="+taskids+sheetname+datatype + "&pageFrom=" + _this.pageFrom + "&dataType=" + _this.dataType ;
               window.location.href = url;
            },
            onCancel() { },
        });
    }

    @action
    isCanCancel = (ids) => {
        let params = { "taskids": ids };
        let modelStore2 = new ModelStore();
        Apis.isCanCancel(params).then(data => {
            // console.log(JSON.stringify(data));
            let canCancelTaskids = [];
            canCancelTaskids = data.canCancelTaskids;
            if(Array.isArray(canCancelTaskids) && canCancelTaskids.length === 0){
                message.warning(getLabel(501160,"选中项已被废弃,不能再次废弃！") );
                return ;
            }
            if (data.containCancel) {
                let _this =  this;
                Modal.confirm({
                    cancelText: `${getLabel(201, '取消')}`,
                    okText: `${getLabel(826, '确定')}`,
                    title: getLabel(15172, "系统提示"),
                    content: `${getLabel(501162,"选中项包含无效数据，是否确认要跳过无效数据？")}`,
                    onOk() {
                        modelStore2.cancelTaskBatch(canCancelTaskids);
                        params.callBack = _this.onSearch;
                        if (typeof (params.callBack === "function")) {
                            params.callBack();
                        }
                    },
                    onCancel() { },
                });
            } else {
                this.showConfirmBatch(canCancelTaskids, "19", getLabel(15172, "系统提示"), getLabel('501173',"该操作会同时废弃所有子任务，确认废弃？"), BtnType.getListRefresh("19"));
            }
        })
    }
    @action
    getcolumnsNum(num){
      this.columnsNum = num;
    }
    @action
    clear(){
      this.selectedTreeKey = 0;
    }
}
